<?php
//рус
include_once(_APP_PATH. "business/groups/groups_mapper.php");
class groups_admin_http_web extends controller_prototype_class
{
	private $_groupsMapper;
	private $_moduleId;
	private $_ctrlId;
	private $_id; 
	
    protected function ControllerInit()
    {
        
    } 
    protected function PrimaryActionInit ($basicActionName)
    {
        $this->GetModule()->GetDecorator()->SetMenuActiveElement('access/groups');   
    }   

    private function GetMapper()
    {
		if (!$this->_groupsMapper) $this->_groupsMapper = GroupsMapper::GetInstance($this->User()); 
		return $this->_groupsMapper;     	
    }    
    
    /**
		экшен по-умолчанию
	*/
    public function PrAction ()
    {
        $this->out_groupsPr();
    }
    
    private function GetQueryId()
    {
    	$this->_id = intval($this->Request()->get('id'));
        if ($this->_id)
        {
			$group = $this->GetMapper()->GetById($this->_id);
			if (!$group) 
			{
				$this->_id = 0;      	
			}
        } 
        return $this->_id;    	
    }
    
    private function GetQueryModuleId()
    {
    	$this->_moduleId = $this->Request()->get('ctrlid');
        if (!$this->GetMapper()->GetModuleById($this->_moduleId))
        {
            $this->_moduleId = $this->GetModule()->GetId();        	
        }  
        return $this->_moduleId;	
    }    
    
    private function GetQueryCtrlId()
    {
    	if (!$this->GetQueryModuleId())
    	{
			$this->_ctrlId = 0;
			return $this->_ctrlId;    		
    	}
    	
    	$this->_ctrlId = intval($this->Request()->get('modid'));
    	$ctrls = $this->GetMapper()->GetCtrlsById($this->_moduleId);
        if (!isset($ctrls[$this->_ctrlId]))
        {
            $this->_ctrlId = 0;        	
        }  
        
        return $this->_ctrlId;	
    }     
    
    public function save_groupPrAction ()
    {
   		if (!$this->GetQueryId()) $group = $this->GetMapper()->GetNew();     	
    	else $group = $this->GetMapper()->GetById($this->_id);
   		
        $group->SetTitle($this->Request()->getPost('title'));
        $group->SetParentId(intval($this->Request()->getPost('parent_id')));

        if (!$this->GetMapper()->SaveGroup($group)) 
        {
        	if ($this->GetMapper()->IsError())
        	{
            	$this->Libs()->messanger->createMessage($this->GetMapper()->GetErrorMessage(), MESSAGE_ERROR);
	       		$this->add_groupPr($group);
	       		return;             	
        	}        
        } 
        else
        {
            $this->Libs()->messanger->createMessage('Группа сохранена');
        }

       	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 
	        									 'ctrl' => 'groups')); 
    }
    
    public function add_groupPrAction ($group = null)
    {
        if (!$group)
        {
	   		if (!$this->GetQueryId() || !in_array($this->_id, $this->User()->GetAvailableGroups())) $group = $this->GetMapper()->GetNew();
	   		else $group = $this->GetMapper()->GetById($this->_id); 
        }     	
    	
		$gr = $this->User()->GetGrantedGroups();
		array_unshift($gr, $this->User()->GetGroupId());
		$gr = array_unique(array_merge($gr, $this->User()->GetAvailableGroups()));        
        if ($group->GetId())
        {
        	$unsGroups = $this->GetMapper()->GetSubGroupsIds($group->GetId(), true);
        	$unsGroups[] = $group->GetId();
        	$gr = array_diff($gr, $unsGroups);
        }

        $this->actionTitle = 'Группы';
        $t = $this->GetTemplator();
        $t->mapper = $this->GetMapper();
        $t->group = $group;
        $t->parentGroups = $gr;
        $t->user = $this->User();
        $this->LoadTemplate ($t->render('groups/_addgroup.phtml'));
    }
    
    public function out_groupsPrAction ()
    {
        $this->actionTitle = 'Группы';
        $t = $this->GetTemplator();
        $t->mapper = $this->GetMapper();
        $t->user = $this->User();
        $this->LoadTemplate ($t->render('groups/_groups.phtml'));
    }
    
    public function del_groupPrAction ()
    {
    	if (!$this->GetQueryId() || !in_array($this->_id, $this->User()->GetAvailableGroups()))
    	{
            $this->Libs()->messanger->createMessage('Группа не найдена', MESSAGE_ERROR);
	       	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 
		        									 'ctrl' => 'groups'));     		
    	}
    	
        if (!$this->GetMapper()->DelGroup($this->_id)) 
        {
            $this->Libs()->messanger->createMessage('Не удалось удалить группу', MESSAGE_ERROR);
        }
        else 
        {
			$this->Libs()->messanger->createMessage('Группа удалена');        	
        }
        
       	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 
	        									 'ctrl' => 'groups')); 
    }
    
    public function view_groupPrAction ()
    {
        if (!$this->GetQueryId() || !in_array($this->_id, $this->User()->GetAvailableGroups()))
        {
            $this->Libs()->messanger->createMessage('Группа не найдена', MESSAGE_ERROR);
	       	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 
		        									 'ctrl' => 'groups'));        	
        }

        if (!$this->GetQueryModuleId())
        {
            $this->Libs()->messanger->createMessage('Модуль не найден', MESSAGE_ERROR);
	       	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 
		        									 'ctrl' => 'groups'));          	
        }
        
        $group = $this->GetMapper()->GetById($this->_id);
        $parentGroup = $this->GetMapper()->GetById($group->GetParentId());
        
        if (!$parentGroup)
        {
            $this->Libs()->messanger->createMessage('Группа не найдена', MESSAGE_ERROR);
	       	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 
		        									 'ctrl' => 'groups'));         	
        }
        
        $avCtrls = $this->GetMapper()->GetCtrlsById($this->_moduleId);
        
        if (!$this->GetMapper()->IsSuperUserGroup($parentGroup->GetId()))
        {	
	        $moduleAccess = $this->GetMapper()->GetGroupsAccess($parentGroup->GetId(), $this->_moduleId);
	        if (isset($moduleAccess[$parentGroup->GetId()][$this->_moduleId]))
	        {     
	        	$ctrls = array();   	
	        	foreach ($avCtrls as $avKey => $av)
	        	{
	        		if ($this->GetMapper()->CheckAccess($moduleAccess[$parentGroup->GetId()][$this->_moduleId], $avKey))
	        		{
	        			$ctrls[$avKey] = $av;
	        		}
	        	}
	        	$avCtrls = $ctrls;
	        }
	        else 
	        {
	        	$avCtrls = array();
	        }
        }
                
        $this->actionTitle = 'Контроллеры';
        $t = $this->GetTemplator();
        $t->moduleId = $this->_moduleId;
        $t->mapper = $this->GetMapper();
        $t->group = $group;
        $t->ctrls = $avCtrls;
        $this->LoadTemplate ($t->render('groups/_controllers.phtml'));
        $this->GetModule()->GetDecorator()->SetSecondAction('Left Sidebar', 'left_block', 'groups');
    }
    public function out_modules()
    {
        $t = $this->GetTemplator();
        $t->moduleId = $this->_moduleId;
        $t->groupId = $this->_id;
        $t->data = array();
        
        $modules = SysLoader::GetModuleCollection()->GetModuleList();
        foreach ($modules as $mod)
        {
        	//if (!$this->GetMapper()->CheckAccess(false)) continue;
        	$t->data[$mod['id']] = $mod;
        }
 
        return $t->render('groups/_modules_list.phtml');
    }
    public function view_modulePrAction ()
    {
        if (!$this->GetQueryId() || !in_array($this->_id, $this->User()->GetAvailableGroups()))
        {
            $this->Libs()->messanger->createMessage('Группа не найдена', MESSAGE_ERROR);
	       	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 
		        									 'ctrl' => 'groups'));        	
        }

        if (!$this->GetQueryCtrlId())
        {
            $this->Libs()->messanger->createMessage('Контроллер не найден', MESSAGE_ERROR);
	       	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 
		        									 'ctrl' => 'groups'));         	
        }
        
        $group = $this->GetMapper()->GetById($this->_id);
        $parentGroup = $this->GetMapper()->GetById($group->GetParentId());
        
        if (!$parentGroup)
        {
            $this->Libs()->messanger->createMessage('Группа не найдена', MESSAGE_ERROR);
	       	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 
		        									 'ctrl' => 'groups'));        	
        }
        
        $ctrlsActions = $this->GetMapper()->GetCtrlActionsById($this->_moduleId, $this->_ctrlId);       
        $moduleAccess = $this->GetMapper()->GetGroupsAccess(array($group->GetId(), $parentGroup->GetId()), $this->_moduleId);
        
        if (!$this->GetMapper()->IsSuperUserGroup($parentGroup->GetId()))
        {
	        if (isset($moduleAccess[$parentGroup->GetId()][$this->_moduleId]))
	        {        	
	        	$parentModuleAccess = $moduleAccess[$parentGroup->GetId()][$this->_moduleId];	        	
	        	$ctrlsIds = array();
	        	while (list($k, $v) = each($ctrlsActions))
	        	{
				    if (!$this->GetMapper()->CheckAccess($parentModuleAccess, $this->_ctrlId, $k)) continue;
				    $ctrlsIds[$k] = $v;	        		
	        	}
        	
	        	$ctrlsActions = $ctrlsIds;
	        }
	        else 
	        {
	        	$ctrlsActions = array();
	        }
        }        
        
        if (isset($moduleAccess[$group->GetId()][$this->_moduleId]))
        { 
        	$curModuleAccess = $moduleAccess[$group->GetId()][$this->_moduleId];
       	    while (list($k) = each($ctrlsActions))
        	{
			    if (!$this->GetMapper()->CheckAccess($curModuleAccess, $this->_ctrlId, $k)) continue;
			    $ctrlsActions[$k]['enabled'] = true;	        		
        	}   
        	reset($ctrlsActions);     	         
        }
        
        $this->actionTitle = 'Экшены';
        $t = $this->GetTemplator();
        $t->moduleId = $this->_moduleId;
        $t->ctrlId = $this->_ctrlId;
        $t->group = $group;
        $t->mapper = $this->GetMapper();
        
        $ctrls = $this->GetMapper()->GetCtrlsById($this->_moduleId);
        $t->ctrl = $ctrls[$this->_ctrlId];
        $t->ctrlActions = $ctrlsActions;
        
        $this->LoadTemplate ($t->render('groups/_modactions.phtml'));
        $this->GetModule()->GetDecorator()->SetSecondAction('Left Sidebar', 'left_block', 'groups');
    }
    public function save_modulePrAction ()
    {
        if (!$this->GetQueryId())
        {
            $this->Libs()->messanger->createMessage('Группа не найдена', MESSAGE_ERROR);
	       	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 
		        									 'ctrl' => 'groups'));        	
        }    	
    	
        if (!$this->GetQueryCtrlId())
        {
            $this->Libs()->messanger->createMessage('Контроллер не найден', MESSAGE_ERROR);
	       	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 
		        									 'ctrl' => 'groups'));         	
        }        
        
        $actions = (array)$this->Request()->getPost('act');
        $result = $this->GetMapper()->SaveGroupAccess($this->_id, $this->_moduleId, $this->_ctrlId, $actions);
        if (!$result) 
        {
            $this->Libs()->messanger->createMessage('Не удалось сохранить доступ', MESSAGE_ERROR);
	       	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 'ctrl' => 'groups', 'action' => 'view_group', 'id' => $this->_id , 'ctrlid' => $this->_moduleId));             
        }
        
        $this->Libs()->messanger->createMessage('Доступ сохранён');
        MozgRoute::Get('http')->Redirect(array('module' => 'admin', 'ctrl' => 'groups', 'action' => 'view_group', 'id' => $this->_id , 'ctrlid' => $this->_moduleId));
    }
    
    public function left_block ()
    {
        $t = $this->GetTemplator();
        $group = $this->GetMapper()->GetById($this->_id);
        $t->title = 'Группа "' . $group->GetTitle() . '"';
        $t->content = $this->out_modules();
        return $t->render('_left_block_template.phtml');
    }    
    protected function LoadTemplate ($content)
    {
        $t = $this->GetTemplator();
        $t->title = $this->actionTitle;
        $t->content = $content;
        $this->Response()->SetBody($t->render('_main_block_template.phtml'));
    }
}